<?php

namespace app\agent\controller;

use app\models\{AgentArea, Agent as Agents, Region, AgentLog, Cate, Product, Riderlist, RiderMoneyLog, RiderStreet, Withdraw, Promo, Config, Order, User as Users, Pkey, Car, Coupon};
use think\Db;
use think\Validate;
use app\facade\Mns;
use app\facade\Redis;
use EasyWeChat\Factory;

class Agent extends Base
{


    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Agents();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['status', 'in', [1, 2]];
            $where[] = ['top', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['accounts|nickname|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['type'])) {
                $wheres = array();
                $wheres[] = ['type', '=', $post['type']];
                switch ($post['type']) {
                    case '2':
                        if (!empty($post['city'])) {
                            $wheres[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $wheres[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '3':
                        if (!empty($post['area'])) {
                            $wheres[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $wheres[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $wheres[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '4':
                        if (!empty($post['street'])) {
                            $wheres[] = ['street', '=', $post['street']];
                        } elseif (!empty($post['area'])) {
                            $wheres[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $wheres[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $wheres[] = ['province', '=', $post['province']];
                        }
                        break;
                    default:
                        break;
                }
                $agents = (new AgentArea())->distinct(true)->where($wheres)->column('agentid');
                $where[] = ['id', 'in', $agents];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['product'] = (new Product())->where(['agentid' => $lists['id'], 'isdel' => 1])->count();
                $lists['btmoneys'] = (new Coupon())->where(['agentid' => $lists['id'], 'types' => 2, 'status' => 1, 'endstatus' => 1])->sum('btmoney'); //未使用
                $lists['btmoneys1'] = (new Coupon())->where(['agentid' => $lists['id'], 'types' => 2, 'status' => [1, 2], 'endstatus' => 2])->sum('btmoney'); //已使用
                $lists['btmoneys2'] = (new Coupon())->where(['agentid' => $lists['id'], 'types' => 2, 'status' => 2, 'endstatus' => 1])->sum('btmoney'); //使用中
                $lists['agentname'] = '无';
                if ($lists['top'] > 0) {
                    $agent = (new Agents())->where('id', $lists['top'])->find();
                    if (!empty($agent)) {
                        $lists['agentname'] = $agent['nickname'] . '(' . $agent['accounts'] . ')';
                    }
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    
    public function riderlat()
    {
        $id = $this->request->get('id/d', 0);
        $startime = strtotime(date('Y-m-d'));
        $getlats = Redis::zRangeByScore('getlatlonarr' . $id, $startime, time());
        if (count($getlats) < 15) {
            $getlats = Redis::zRange('getlatlonarr' . $id, 0, 109, true); // 返回分数从低到高排序的前10名及分数
        }
        foreach ($getlats as $k => &$getlat) {
            $getlat = explode(',', $getlat);
            if (count($getlat) < 2 || $getlat[0] == 'undefined') {
                unset($getlats[$k]);
            }
        }
        $getlats = array_values($getlats);
        return view('', ['getlats' => $getlats]);
    }

    public function index_exc()
    {
        if ($this->request->isAjax()) {
            $data = input();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            //查询代理是否已存在
            $agent = (new Agents())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($agent)) {
                return json(['code' => 1, 'msg' =>  '代理不存在或已冻结']);
            }
            //根据分类导入
            $text = '';
            try {
                //查找子分类下系统产品
                $products = (new Product())->where(['agentid' => 0, 'isdel' => 1, 'isshow' => 1])->select();
                /************1、判断产品是否需要导入*************/
                foreach ($products as $product) {
                    $sproduct = (new Product())
                        ->whereOr(function ($query) use ($product, $data) {
                            $query->where(['isshow' => 1, 'topid' => $product['id'], 'agentid' => $data['id'], 'isdel' => 1]);
                        })->whereOr(function ($query) use ($product, $data) {
                            $query->where(['isshow' => 1, 'title' => $product['title'], 'agentid' => $data['id'], 'isdel' => 1]);
                        })->find();
                    //不存在就导入产品
                    if (empty($sproduct)) {
                        $drpro = [
                            'agentid' => $data['id'],
                            'cate' => $product['cate'],
                            'type' =>  $product['type'],
                            'price' => $product['price'],
                            'price1' => $product['price1'],
                            'price2' => $product['price2'],
                            'iskey' => $product['iskey'],
                            'title' => $product['title'],
                            'descs' => $product['descs'],
                            'images' => $product['images'],
                            'isshow' => $product['isshow'],
                            'sort' => $product['sort'],
                            'topid' => $product['id'],
                        ];
                        $res = (new Product())->allowfield(true)->save($drpro);
                        if (!$res) {
                            $text = $text . '产品[' . $product['title'] . ']导入失败<br/>';
                            continue;
                        }
                    }
                }
                //查找待导入套餐
                $promos = (new Promo())->where(['agentid' => 0, 'status' => 1, 'type' => 1])->select();
                /************1、判断套餐是否需要导入*************/
                foreach ($promos as $promo) {
                    $spromos = (new Promo())
                        ->whereOr(function ($query) use ($promo, $data) {
                            $query->where(['status' => 1, 'topid' => $promo['id'], 'agentid' => $data['id']]);
                        })->whereOr(function ($query) use ($promo, $data) {
                            $query->where(['status' => 1, 'title' => $promo['title'], 'agentid' => $data['id']]);
                        })->find();
                    //不存在就导入套餐
                    if (empty($spromos)) {
                        $drpromos = [
                            'agentid' => $data['id'],
                            'type' => $promo['type'],
                            'descs' => $promo['descs'],
                            'images' => $promo['images'],
                            'money' => $promo['money'],
                            'title' => $promo['title'],
                            'coupon' => $promo['coupon'],
                            'contents' => $promo['contents'],
                            'topid' => $promo['id'],
                        ];
                        $res = (new Promo())->allowfield(true)->save($drpromos);
                        if (!$res) {
                            $text = $text . '套餐[' . $promo['title'] . ']导入失败<br/>';
                            continue;
                        }
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        }
    }

    public function agent_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'nickname' => 'require|chsAlphaNum|length:4,50',
                'accounts' => 'require|alphaNum|length:6,50',
                'mobile' => 'require',
            ], [
                'nickname.require' => '备注不能为空',
                'nickname.length' => '备注长度控制在6-20个字符',
                'nickname.chsAlphaNum' => '备注只能是汉字、字母和数字',
                'accounts.require' => '账号不能为空',
                'accounts.alphaNum' => '账号只能是字母和数字',
                'accounts.length' => '账号长度控制在6-50个字符',
                'mobile.require' => '手机不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '手机格式不正确');
            }
            //查询是否有权限
            $qxhave1 = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => [4, 5]])->find();
            if (!empty($qxhave1)) {
                return json(['code' => 1, 'msg' => '您没有该功能权限']);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Agents();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where(['accounts' => $data['accounts'], 'status' => [1, 2]])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                if ($haveshop['top'] != $this->request->agent['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '无操作权限']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($res) {
                    return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
                }
                return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
            } else {
                switch ($data['type']) {
                    case '3':
                        if (empty($data['province'])) {
                            return json(['code' => 1, 'msg' => '请选择省份']);
                        }
                        if (empty($data['city'])) {
                            return json(['code' => 1, 'msg' => '请选择城市']);
                        }
                        if (empty($data['area'])) {
                            return json(['code' => 1, 'msg' => '请选择区域']);
                        }
                        //查询是否有权限
                        $qxhave = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                        if (empty($qxhave)) {
                            return json(['code' => 1, 'msg' => '您没有该区域权限']);
                        }
                        $data['street'] = 0;
                        break;
                    case '4':
                        if (empty($data['province'])) {
                            return json(['code' => 1, 'msg' => '请选择省份']);
                        }
                        if (empty($data['city'])) {
                            return json(['code' => 1, 'msg' => '请选择城市']);
                        }
                        if (empty($data['area'])) {
                            return json(['code' => 1, 'msg' => '请选择区域']);
                        }
                        if (empty($data['street'])) {
                            return json(['code' => 1, 'msg' => '请选择街道']);
                        }
                        //查询是否有权限
                        $qxhave1 = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 3, 'area' => $data['area']])->find();
                        //查询是否有权限
                        $qxhave = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                        if (empty($qxhave) && empty($qxhave1)) {
                            return json(['code' => 1, 'msg' => '您没有该区域权限']);
                        }
                        break;
                    case '5':
                        if (empty($data['province'])) {
                            return json(['code' => 1, 'msg' => '请选择省份']);
                        }
                        if (empty($data['city'])) {
                            return json(['code' => 1, 'msg' => '请选择城市']);
                        }
                        if (empty($data['area'])) {
                            return json(['code' => 1, 'msg' => '请选择区域']);
                        }
                        if (empty($data['street'])) {
                            return json(['code' => 1, 'msg' => '请选择街道']);
                        }
                        //查询是否有权限
                        $qxhave1 = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 3, 'area' => $data['area']])->find();
                        //查询是否有权限
                        $qxhave = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                        if (empty($qxhave) && empty($qxhave1)) {
                            return json(['code' => 1, 'msg' => '您没有该区域权限']);
                        }
                        break;
                    default:
                        return json(['code' => 1, 'msg' => '代理区域类型错误']);
                        break;
                }
                if ($data['type'] != 5) {
                    //查询负责区域是否已存在
                    $businessarea = (new AgentArea())->where([
                        'type' => $data['type'],
                        'province' => $data['province'],
                        'city' => $data['city'],
                        'area' => $data['area'],
                        'street' => $data['street']
                    ])->find();
                    if (!empty($businessarea)) {
                        return json(['code' => 1, 'msg' => '管理区域已添加或已分配']);
                    }
                }
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $data['top'] = $this->request->agent['id'];
                Db::startTrans();
                try {
                    $agentid = $model->strict(false)->insertGetId($data);
                    (new AgentArea())->allowField(true)->save([
                        'type' => $data['type'],
                        'province' => $data['province'],
                        'city' => $data['city'],
                        'area' => $data['area'],
                        'street' => $data['street'],
                        'agentid' => $agentid,
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
        } else {
            $model = new Agents();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'province' => (new Region())->where(['level' => 1])->select(),
                'row' => $row
            ]);
        }
    }

    public function agentarea()
    {
        if ($this->request->isAjax()) {
            $model = new AgentArea();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['accounts|nickname|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            $agents = (new Agents())->where('top', $this->request->agent['id'])->column('id');
            $where[] = ['agentid', 'in',  $agents];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $row['agent_name'] = (new Agents())->where(['id' => $row['agentid']])->value('nickname') ?? '';
                $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '无';
                $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '无';
                $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '无';
                $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select(),
                'agent' => (new Agents())->where('top', $this->request->agent['id'])->field('id,nickname,accounts')->where(['status' => [1, 2]])->select(),
            ]);
        }
    }

    public function agentarea_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'agentid' => 'require',
                'type' => 'require|in:3,4,5'
            ], [
                'agentid.require' => '代理不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            switch ($data['type']) {
                case '3':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    //查询是否有权限
                    $qxhave = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                    if (empty($qxhave)) {
                        return json(['code' => 1, 'msg' => '您没有该区域权限']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 4, 'area' => $data['area']])->find();
                    if (!empty($havearea)) {
                        return json(['code' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['street'] = 0;
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['code' => 1, 'msg' => '请选择街道']);
                    }
                    //查询是否有权限
                    $qxhave1 = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 3, 'area' => $data['area']])->find();
                    //查询是否有权限
                    $qxhave = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                    if (empty($qxhave) && empty($qxhave1)) {
                        return json(['code' => 1, 'msg' => '您没有该区域权限']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['code' => 1, 'msg' => '已拥有高级别的区域管理，无需再添加低级别区域管理']);
                    }
                    break;
                case '5':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['code' => 1, 'msg' => '请选择街道']);
                    }
                    //查询是否有权限
                    $qxhave1 = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 3, 'area' => $data['area']])->find();
                    //查询是否有权限
                    $qxhave = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $data['city']])->find();
                    if (empty($qxhave) && empty($qxhave1)) {
                        return json(['code' => 1, 'msg' => '您没有该区域权限']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['code' => 1, 'msg' => '已拥有高级别的区域管理，无需再添加低级别区域管理']);
                    }
                    break;
                default:
                    return json(['code' => 1, 'msg' => '代理区域类型错误']);
                    break;
            }
            if ($data['type'] != 5) {
                //查询负责区域是否已存在
                $businessarea = (new AgentArea())->where([
                    'type' => $data['type'],
                    'province' => $data['province'],
                    'city' => $data['city'],
                    'area' => $data['area'],
                    'street' => $data['street']
                ])->find();
                if (!empty($businessarea)) {
                    return json(['code' => 1, 'msg' => '管理区域已添加或已分配']);
                }
            }
            $res = (new AgentArea())->allowfield(true)->save($data);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new AgentArea())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            $agent = (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2], 'top' => $this->request->agent['id']])->select();
            if (empty($row)) {
                $agentid = $this->request->get('agentid/d', 0);
                if (!empty($agentid)) {
                    $row['agentid'] = $agentid;
                }
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'agent' => $agent
            ]);
        }
    }

    public function agentarea_quan()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'ploygongeo' => 'require'
            ], [
                'id.require' => 'ID不能为空',
                'ploygongeo.require' => '坐标集不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $model = new AgentArea();
            //查找店铺名称、账号是否已经被使用
            $have = $model->where(['id' => $data['id'], 'type' => 5])->find();
            if (empty($have)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请重试']);
            }
            $text = null;
            if (count($data['ploygongeo']) > 0) {
                $data['ploygongeo'][] = $data['ploygongeo'][0];
            }
            $ploygongeoarr = [];
            //范围验证查询
            $arrfw = [];
            foreach ($data['ploygongeo'] as $ploygon) {
                # code...
                if (count($ploygon) != 2) {
                    return json(['code' => 1, 'data' => [], 'msg' => '数据错误，请重试']);
                }
                $arrfw[] = implode(',', $ploygon);
                $ploygon = implode(' ', $ploygon);
                $ploygongeoarr[] = $ploygon;
            }
            //需要查询的数组
            $adcodes = [];
            $key = env('map.key');
            foreach ($arrfw as $arrfws) {
                $url = 'https://restapi.amap.com/v3/geocode/regeo';
                $res = api_curl($url, ['location' => $arrfws, 'key' => $key, 'extensions' => 'base']);
                if ($res['status'] == 1 && !empty($res['regeocode']['addressComponent']['adcode'])) {
                    //代理端通过区域代码验证权限
                    $adcodesm = $res['regeocode']['addressComponent']['adcode'] ?? 0;
                    //查询是否有权限
                    $qxhave1 = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 3, 'area' => $adcodesm])->find();
                    //查询是否有权限
                    $parent_id = (new Region())->where(['level' => 3, 'area_code' => $adcodesm])->value('parent_id');
                    $city = (new Region())->where(['level' => 2, 'id' => $parent_id])->value('area_code') ?? 0;
                    $qxhave = (new AgentArea())->where(['agentid' => $this->request->agent['id'], 'type' => 2, 'city' => $city])->find();
                    if (empty($qxhave) && empty($qxhave1)) {
                        return json(['code' => 1, 'data' => [], 'msg' => '超出区域权限范围']);
                    }
                } else {
                    return json(['code' => 1, 'data' => [], 'msg' => '坐标错误或超出范围，请适当调整后再试']);
                }
            }
            $ploygongeoarr = implode(',', $ploygongeoarr);
            $text = 'POLYGON((' . $ploygongeoarr . '))';
            //查询重叠数值
            $sql =  "st_intersects(ST_PolygonFromText(ploygongeo),ST_PolygonFromText('" . $text . "')) = 1";
            $agentarea = (new AgentArea())->where('id', '<>', $data['id'])->where('type', 5)->where($sql)->find();
            if (!empty($agentarea)) {
                return json(['code' => 1, 'data' => [], 'msg' => '该区域与已分配区域重叠，请检查后重新划分']);
            }
            $res = $model->allowfield(true)->save(['ploygongeo' => $text], ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new AgentArea();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->field('substring(ploygongeo,10,length(ploygongeo)-11) as ploygongeo,id')->find();
            $arr = [];
            if ($row) {
                $row['ploygongeo'] = explode(',', $row['ploygongeo']) ?? [];
                $row['ploygongeo'] = array_slice($row['ploygongeo'], 0, -1);
                foreach ($row['ploygongeo'] as $key => $ploygongeo) {
                    $ploygongeo = explode(' ', $ploygongeo) ?? [];
                    $arr[] = $ploygongeo;
                }
            }
            $istrue = 1;
            foreach ($arr as $arrs) {
                if (count($arrs) != 2 && $istrue == 1) {
                    $istrue = 2;
                }
            }
            if ($istrue == 2) {
                $arr = [];
            }
            //获取全部区域
            $model = new AgentArea();
            $agents = (new Agents())->where('top', $this->request->agent['id'])->column('id');
            if (count($agents) <= 0) {
                $agents = [-1];
            }
            $lists = $model->where('type', 5)->where(['agentid' => $agents])->where('id', '<>', $id)->field('substring(ploygongeo,10,length(ploygongeo)-11) as ploygongeo,id')->select();
            $arr2 = [];
            foreach ($lists as $list) {
                $list['ploygongeo'] = explode(',', $list['ploygongeo']) ?? [];
                $list['ploygongeo'] = array_slice($list['ploygongeo'], 0, -1);
                foreach ($list['ploygongeo'] as $key => $ploygongeos) {
                    $ploygongeos = explode(' ', $ploygongeos) ?? [];
                    $arr2[$list['id']][] = $ploygongeos;
                }
            }
            array_multisort($arr2);
            return view('', [
                'row' => $row,
                'arr' => $arr,
                'arr2' => $arr2
            ]);
        }
    }

    public function rmoneylog()
    {
        if ($this->request->isAjax()) {
            $model = new RiderMoneyLog();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $user_id = input('id/d') ?? 0;
            $where = array();
            $where[] = ['user_id', '=', $user_id];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function rmoney_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'moneys' => 'require|gt:0',
                'type' => 'require|in:1,2',
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
                'moneys.require' => '金额不能为空',
                'moneys.gt' => '金额必须大于0',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $haverider = (new RiderStreet())->where(['riderid' => $data['id'], 'status' => [1, 2]])->value('agentid') ?? 0;
            if ($this->request->agent['id'] != $haverider) {
                $this->result([], 1, '您无该人员管理权限');
            }
            $data['desc'] = empty($data['desc']) ? '资产变更' : $data['desc'];
            if ($data['type'] == 1) {
                $money = abs($data['moneys']);
            } else {
                $money = -abs($data['moneys']);
            }
            $user = (new Riderlist())->where('id', $data['id'])->find();
            if (empty($user)) {
                return json(['code' => 1, 'data' => [], 'msg' => '账号不存在']);
            }
            Db::startTrans();
            try {
                (new Riderlist())->MondyEdit($user['id'], $user['money'], $money, 3, 0, $data['desc'], 0);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
    }

    public function agent_qrcode()
    {

        $id = $this->request->agent['id'];
        if (empty($id)) {
            return view();
        }
        $name = 'agentid' . $id . '.png';
        $qcode = url('/rider/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/rider/";
        $config = config('wechat.');
        try {
            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('rider=0&agentid=' . $id, [
                'page'  => 'pages/index/getCoupon',
                'width' => 600
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $rm->save($path, $name);
            }
        } catch (\Exception $e) {
            return view();
        }
        return view('', [
            'url' => $qcode
        ]);
    }

    public function sendmess()
    {
        $CheckCode = (new Mns())->send($this->request->agent['mobile']);
        if (!$CheckCode) {
            return json(['code' => 1, 'msg' => '发送失败,请重试']);
        }
        return json(['code' => 200, 'msg' => '短信已发送至手机' . $this->request->agent['mobile']]);
    }

    public function promo()
    {
        if ($this->request->isAjax()) {
            $model = new Promo();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', '=', $post['type']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function promo_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'money' => 'require|gt:0'
            ], [
                'title.require' => '活动不能为空',
                'money.require' => '支付金额必须填写',
                'money.gt' => '支付金额必须大于0',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['agentid'] = $this->request->agent['id'];

            if (!is_array($data['coupon'])) {
                return json(['code' => 1, 'msg' => '优惠券数据出错']);
            }
            if (!empty($data['code']) && (!preg_match('/^[A-Z]+$/', $data['code']) || mb_strlen($data['code']) > 4)) {
                return json(['code' => 1, 'msg' => '编码前缀请输入1-4位大写字母']);
            }
            $data['coupon'] = json_encode($data['coupon'], true);
            if (empty($data['id'])) {
                $res = (new Promo())->allowfield(true)->save($data);
            } else {
                $res = (new Promo())->allowfield(true)->save($data, ['id' => $data['id']]);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Promo())->where(['id' => $id])->find();
            if ($row) {
                $row['coupon'] = json_decode($row['coupon'], true);
            }
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function keys2()
    {
        if ($this->request->isAjax()) {
            $model = new Pkey();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['id', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['code'])) {
                $where[] = ['code', 'like', '%' . $post['code'] . '%'];
            }
            if (!empty($post['promoid'])) {
                $where[] = ['promoid', '=', $post['promoid']];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['rider'])) {
                if ($post['rider'] == '-1') {
                    $post['rider'] = 0;
                }
                $where[] = ['rider', '=', $post['rider']];
            }
            $where[] = ['type', '=', 2];
            if (!empty($post['nicknames'])) {
                //搜微信用户
                //用户昵称和绑定手机号
                $user = (new Users())->where('mobile|nickName', 'like', '%' . $post['nicknames'] . '%')->column('id');
                //车辆信息
                $car = (new Car())->where('name|mobile|cards', 'like', '%' . $post['nicknames'] . '%')->column('user_id');
                $arr = array_merge($user, $car);
                $user_id = array_unique($arr);
                if (count($user_id) == 0) {
                    $user_id = [-1];
                }
                $where[] = ['user_id', 'in', $user_id];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                //查询代理
                $promo = (new Promo())->where('id', $lists['promoid'])->find();
                $lists['title'] = $promo['title'];
                $users = [
                    'nickname' => '',
                    'bmobile' => '',
                    'name' => '',
                    'mobile' => '',
                    'cards' => ''
                ];
                $rider = [
                    'name' => '',
                    'mobile' => '',
                ];
                if ($lists['user_id'] > 0) {
                    //用户昵称和绑定手机号
                    $user = (new Users())->where('id', $lists['user_id'])->find();
                    //车辆信息
                    $car = (new Car())->where('user_id', $lists['user_id'])->order('is_default desc')->find();
                    $users = [
                        'nickname' => $user['nickName'] ?? '无',
                        'bmobile' => $user['mobile'] ?? '无',
                        'name' => $car['name'] ?? '无',
                        'mobile' => $car['mobile'] ?? '无',
                        'cards' => $car['cards'] ?? '无'
                    ];
                }
                if ($lists['rider'] > 0) {
                    //用户昵称和绑定手机号
                    $riders = (new Riderlist())->where('id', $lists['rider'])->find();
                    $rider = [
                        'name' => $riders['name'] ?? '无',
                        'mobile' => $riders['mobile'] ?? '无',
                    ];
                }
                $lists['users'] = $users;
                $lists['riders'] = $rider;
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $promo = (new Promo())->field('id,title,agentid,status')->select();
            foreach ($promo as $promos) {
                $promos['agent_name'] = (new Agents())->where(['id' => $promos['agentid']])->value('nickname') ?? '';
            }
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid') ?? [-1];
            return view(null, [
                'promo' => $promo,
                'rider' => (new Riderlist())->field('id,name,mobile')->where(['id' => $riderid])->select()
            ]);
        }
    }

    public function keys_status()
    {
        $id = input('id');
        $status = input('status/d', 0);
        $agentid = $this->request->agent['id'];
        $ids = [];
        if (!empty($id)) {
            $model = new Pkey();
            switch ($status) {
                case '2':
                    if (is_array($id)) {
                        foreach ($id as $idd) {
                            $cate = $model->where(['id' => $idd, 'status' => 1, 'type' => 2, 'agentid' => $agentid])->find();
                            if (!empty($cate)) {
                                $ids[] = $idd;
                            }
                        }
                    } else {
                        $ids[] = $id;
                    }
                    if (count($ids) <= 0) {
                        return json(['code' => 1, 'data' => [], 'msg' => '非审核状态或无可操作内容']);
                    }
                    foreach ($ids as $id) {
                        //兑换码存在查询活动是否还在继续
                        $key = (new Pkey())->where(['id' => $id, 'status' => 1, 'agentid' => $agentid])->find();
                        if (empty($key)) {
                            return json(['code' => 1, 'data' => [], 'msg' => '申请信息不存在']);
                        }
                        $promo = (new Promo())->where(['id' => $key['promoid'], 'status' => 1, 'type' => 1])->find();
                        if (empty($promo)) {
                            return json(['code' => 1, 'data' => [], 'msg' => '活动已关闭']);
                        }
                        $coupons = [];
                        $promo['coupon'] = json_decode($promo['coupon'], true) ?? [];
                        foreach ($promo['coupon'] as $coupon) {
                            $coupon['type'] = implode(',', $coupon['type']);
                            $modelcount = count($coupon['carmodel']);
                            $coupon['carmodel'] = implode(',', $coupon['carmodel']);
                            $number = (int)$coupon['number'] ?? 1;
                            for ($i = 0; $i < $number; $i++) {
                                $coupons[] = [
                                    'type' => 1,
                                    'types' => 2,
                                    'user_id' => $key['user_id'],
                                    'agentid' => $promo['agentid'],
                                    'productid' => $coupon['type'],
                                    'carmodel' => $coupon['carmodel'],
                                    'modelcount' => $modelcount,
                                    'number' => 1,
                                    'status' => 1,
                                    'text' => '申请领卡发放',
                                    'endtime' => date('Y-m-d H:i:s', time() + 86400 * ($coupon['days'] ?? 10000)),
                                    'promo' => $promo['id'],
                                    'keyid' => $key['id'],
                                ];
                            }
                        }
                        Db::startTrans();
                        try {
                            if (count($coupons) > 0) {
                                (new Coupon())->allowfield(true)->saveAll($coupons);
                            }
                            (new Pkey())->where('id', $key['id'])->update(['status' => 2, 'user_id' =>  $key['user_id'], 'ltime' => date('Y-m-d H:i:s')]);
                            Db::commit();
                        } catch (\Exception $e) {
                            Db::rollback();
                            $this->result([], 1, $e->getMessage());
                        }
                    }
                    break;
                case '3':
                    if (is_array($id)) {
                        foreach ($id as $idd) {
                            $cate = $model->where(['id' => $idd, 'status' => 1, 'agentid' => $agentid])->find();
                            if (!empty($cate)) {
                                $ids[] = $idd;
                            }
                        }
                    } else {
                        $ids[] = $id;
                    }
                    if (count($ids) <= 0) {
                        return json(['code' => 1, 'data' => [], 'msg' => '无可操作内容']);
                    }
                    Db::startTrans();
                    try {
                        $model->where(['id' => $ids, 'agentid' => $agentid])->update(['status' => 3]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
                    }
                    break;

                default:
                    # code...
                    break;
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function withdraw()
    {
        if ($this->request->isAjax()) {
            $model = new Withdraw();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['user_id', '=',  $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['name|cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function withdraw_status()
    {
        $id = input('id');
        $status = input('status/s', '0');
        if (!empty($id)) {
            if ($status != 2 && $status != 3) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据状态错误']);
            }
            $model = new Withdraw();
            $cate = $model->where(['id' => $id, 'user_id' => $this->request->agent['id']])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            if ($cate['status'] != 1) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据已审核，无需重复审核']);
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['status' => $status]);
                if ($status == 3) {
                    (new Agents())->MoneyEdit($cate['user_id'], 3, $cate['money'], '取消提现', $cate['id']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function withdraw_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|egt:100|float',
                'name' => 'require',
                'cards' => 'require',
                'bank' => 'require',
                'smscode' => 'require'
            ], [
                'money.require' => '提现金额不能为空',
                'money.gt' => '提现金额不能低于100',
                'money.float' => '提现金额数据不正确',
                'name.require' => '用户名不能为空',
                'cards.require' => '银行卡号不能为空',
                'bank.require' => '所属银行不能为空',
                'smscode.require' => '验证码不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if ($this->request->agent['money'] < $data['money']) {
                return json(['code' => 1, 'msg' => '可提现金额不足']);
            }
            if (!(new Mns())->checkCode($data['smscode'], $this->request->agent['mobile'])) {
                return json(['code' => 1, 'msg' => '验证码错误']);
            }
            $data['user_id'] = $this->request->agent['id'];
            Db::startTrans();
            try {
                (new Withdraw())->allowfield(true)->save($data);
                (new Agents())->MoneyEdit($this->request->agent['id'], 2, -$data['money'], '发起提现', 0);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        } else {
            return view('', [
                'money' => $this->request->agent['money'],
                'fee' => $this->request->agent['handfee'] ?? 0.7,
            ]);
        }
    }

    public function rider()
    {
        if ($this->request->isAjax()) {
            $model = new Riderlist();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['mobile|name|cards', 'like', '%' . $post['title'] . '%'];
            }
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');
            $where[] = ['id', 'in', $riderid];
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['istdz'])) {
                $where[] = ['istdz', '=', $post['istdz']];
            }
            if (!empty($post['street'])) {
                $where[] = ['street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['province', '=', $post['province']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['count']  = (new Order())->where(['orderid' => $lists['id'], 'status' => 4])->count();
                $lists['total']  = (new Order())->where(['orderid' => $lists['id'], 'status' => 4])->sum('ptotal');
                $lists['income'] = 0;
                if ($lists['user_id'] > 0) {
                    $user = (new Users())->where('pid', $lists['user_id'])->column('id');
                    $lists['income'] = (new Order())->where(['user_id' => $user, 'status' => 4, 'agentid' => $this->request->agent['id']])->sum('ptotal');
                    $lists['incomecount'] = (new Order())->where(['user_id' => $user, 'status' => 4, 'agentid' => $this->request->agent['id']])->count();
                } else {
                    $lists['income'] = 0;
                    $lists['incomecount'] = 0;
                }
                //团队长
                if ($lists['pid'] > 0) {
                    $tdzs = (new Riderlist())->where('id', $lists['pid'])->field('name,cards,mobile')->find();
                    if (!empty($tdzs)) {
                        $lists['tdzname'] = $tdzs['name'];
                        $lists['tdzcards'] = $tdzs['cards'];
                        $lists['tdzmobile'] = $tdzs['mobile'];
                    }
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select()
            ]);
        }
    }

    public function rider_status()
    {
        $id = input('id');
        $value = input('value');
        if (!empty($id)) {
            $haverider = (new RiderStreet())->where(['riderid' => $id, 'status' => [1, 2]])->value('agentid') ?? 0;
            if ($this->request->agent['id'] != $haverider) {
                $this->result([], 1, '您无该人员管理权限');
            }
            if (empty($value)) {
                return json(['code' => 1, 'data' => [], 'msg' => '请填写团队长账号']);
            }
            $tdz = (new Riderlist())->where(['mobile' => $value, 'istdz' => 2])->find();
            if (empty($tdz)) {
                return json(['code' => 1, 'data' => [], 'msg' => '账号不存在或非团队长']);
            }
            $rider = (new Riderlist())->where('id', $id)->find();
            if (empty($rider)) {
                return json(['code' => 1, 'data' => [], 'msg' => '师傅信息不存在,请重试']);
            }
            if ($tdz['id'] == $rider['id']) {
                return json(['code' => 1, 'data' => [], 'msg' => '团队长账号不能与师傅账号一致']);
            }

            Db::startTrans();
            try {
                (new Riderlist())->where('id', $rider['id'])->update(['pid' => $tdz['id']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }



    public function rider_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            } elseif (isset($data['password'])) {
                unset($data['password']);
            }
            $haverider = (new RiderStreet())->where(['riderid' => $data['id'], 'status' => [1, 2]])->value('agentid') ?? 0;
            if ($this->request->agent['id'] != $haverider) {
                $this->result([], 1, '您无该人员管理权限');
            }
            $res = (new Riderlist())->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Riderlist())->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }


    public function rider_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Riderlist();
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id'], 'riderid' => $id])->column('id');
            if (count($riderid) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '操作失败,无操作权限']);
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                (new RiderStreet())->where(['riderid' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function riderstreet()
    {
        if ($this->request->isAjax()) {
            $model = new RiderStreet();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['rs.agentid', '=', $this->request->agent['id']];
            if (!empty($post['rider'])) {
                $where[] = ['rs.riderid', '=', $post['rider']];
            }
            if (!empty($post['title'])) {
                $where[] = ['r.mobile|r.name|r.cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['r.status', '=', $post['status']];
            }
            if (!empty($post['street'])) {
                $where[] = ['rs.street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['rs.area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['rs.city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['rs.province', '=', $post['province']];
            }
            $count = $model->alias('rs')->join('riderlist r', 'rs.riderid = r.id')->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->alias('rs')->join('riderlist r', 'rs.riderid = r.id')
                ->where($where)->order(['rs.status' => 'asc', "rs.id" => 'desc'])->field('rs.*,r.mobile,r.name,r.cards,r.positive,r.negative')->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $address = getdrees($lists['street'], 2);
                $lists['province_text'] = $address['province'];
                $lists['city_text'] = $address['city'];
                $lists['area_text'] = $address['area'];
                $lists['street_text'] = $address['street'];
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select()
            ]);
        }
    }


    public function riderstreet_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'riderid' => 'require',
                'street' => 'require'
            ], [
                'riderid.require' => '师傅不能为空',
                'street.require' => '街道不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['agentid'] = $this->request->agent['id'];
            $data['status'] = 2;
            //查询是否有当前街道添加权限
            // $ishave = geauthagents($data['agentid'], $data['street'], 0, 0);
            // if (empty($ishave) || $ishave == 1) {
            //     return json(['code' => 1, 'msg' => '操作失败,您无该街道操作权限']);
            // }
            $haverider = (new RiderStreet())->where(['riderid' => $data['riderid'], 'status' => [1, 2]])->value('agentid') ?? 0;
            if (!empty($haverider) && $data['agentid'] != $haverider) {
                $this->result([], 1, '此街道与您已申请街道不属于同一管理人员,无法申请');
            }
            //查询负责区域是否已存在
            $riderstreet = (new RiderStreet())->where([
                'riderid' => $data['riderid'],
                'street' => $data['street']
            ])->find();

            if (!empty($riderstreet)) {
                $res = (new RiderStreet())->allowfield(true)->save($data, ['id' => $riderstreet['id']]);
            } else {
                $res = (new RiderStreet())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $row = [];
            $province = (new Region())->where(['level' => 1])->select();
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');
            $rider = (new Riderlist())->where(['id' => $riderid])->field('id,name,mobile')->select();
            $riderid = $this->request->get('riderid/d', 0);
            if (!empty($riderid)) {
                $row['riderid'] = $riderid;
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'rider' => $rider
            ]);
        }
    }


    public function riderstreet_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'riderid' => 'require',
                'street' => 'require'
            ], [
                'riderid.require' => '师傅不能为空',
                'street.require' => '街道不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (count($data['street']) <= 0) {
                return json(['code' => 1, 'msg' => '请选择街道']);
            }
            $data['agentid'] = $this->request->agent['id'];
            $haverider = (new RiderStreet())->where(['riderid' => $data['riderid'], 'status' => [1, 2]])->value('agentid') ?? 0;
            if (!empty($haverider) && $data['agentid'] != $haverider) {
                $this->result([], 1, '此街道与您已申请街道不属于同一管理人员,无法申请');
            }
            try {
                foreach ($data['street'] as $street) {
                    //查询负责区域是否已存在
                    $riderstreet = (new RiderStreet())->where([
                        'riderid' => $data['riderid'],
                        'street' => $street
                    ])->find();
                    //查询是否有当前街道添加权限
                    // $ishave = geauthagents($data['agentid'], $data['street'], 0, 0);
                    // if (empty($ishave) || $ishave == 1) {
                    //     continue;
                    // }
                    $geo = getdrees($street, 3);
                    if (!empty($riderstreet)) {
                        (new RiderStreet())->allowfield(true)->save([
                            'agentid' => $data['agentid'],
                            'riderid' => $data['riderid'],
                            'province' => $geo['province'],
                            'city' => $geo['city'],
                            'area' => $geo['area'],
                            'street' => $geo['street'],
                            'status' => 2
                        ], ['id' => $riderstreet['id']]);
                    } else {
                        (new RiderStreet())->allowfield(true)->save([
                            'agentid' => $data['agentid'],
                            'riderid' => $data['riderid'],
                            'province' => $geo['province'],
                            'city' => $geo['city'],
                            'area' => $geo['area'],
                            'street' => $geo['street'],
                            'status' => 2
                        ]);
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        } else {
            $row = [];
            $province = (new Region())->where(['level' => 1])->select();
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');
            $rider = (new Riderlist())->where(['id' => $riderid])->field('id,name,mobile')->select();
            $riderid = $this->request->get('riderid/d', 0);
            if (!empty($riderid)) {
                $row['riderid'] = $riderid;
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'rider' => $rider
            ]);
        }
    }

    public function riderstreet_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new RiderStreet();
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function riderstreet_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        $status = input('status/d', 0);
        $sz = input('sz/d', 0);
        if (!empty($id) && !empty($field)) {
            if ($status != 2 && $status != 3) {
                return json(['code' => 1, 'data' => [], 'msg' => '操作状态错误，请刷新页面重试']);
            }
            $model = new RiderStreet();
            $cate = $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在或无权限']);
            }
            $pid = 0;
            switch ($field) {
                case 'status':
                    if ($sz == 1) {
                        $value = input('value');
                        if (empty($value)) {
                            return json(['code' => 1, 'data' => [], 'msg' => '请填写团队长账号']);
                        }
                        $tdz = (new Riderlist())->where(['mobile' => $value, 'istdz' => 2])->find();
                        if (empty($tdz)) {
                            return json(['code' => 1, 'data' => [], 'msg' => '账号不存在或非团队长']);
                        }
                        $rider = (new Riderlist())->where('id', $cate['riderid'])->find();
                        if (empty($rider)) {
                            return json(['code' => 1, 'data' => [], 'msg' => '师傅信息不存在,请重试']);
                        }
                        if ($tdz['id'] == $rider['id']) {
                            return json(['code' => 1, 'data' => [], 'msg' => '团队长账号不能与师傅账号一致']);
                        }
                        if ($rider['pid'] > 0) {
                            return json(['code' => 1, 'data' => [], 'msg' => '师傅已设置团队长,如需修改请在师傅列表修改']);
                        }
                        $pid = $tdz['id'] ?? 0;
                    }
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                if ($pid > 0) {
                    (new Riderlist())->where('id', $cate['riderid'])->update(['pid' => $pid]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function product()
    {
        if ($this->request->isAjax()) {
            $model = new Product();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['isdel', '=', 1];
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['type'] =  config()['config']['type'][$lists['type']];
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select()
            ]);
        }
    }


    public function product_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'cate' => 'require',
                'type' => 'require',
            ], [
                'title.require' => '标题不能为空',
                'cate.require' => '分类不能为空',
                'type.require' => '类型不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['agentid'] = $this->request->agent['id'];
            if (!empty($data['id'])) {
                $res = (new Product())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Product())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Product())->where('id', $id)->find();
            if (!empty($row)) {
                $where[] = ['cate', '=', $row['cate']];
                $where[] = ['agentid', '=', $row['agentid']];
            }
            return view('', [
                'row' => $row,
                'cate' => (new Cate())->field('id,name,isshow')->order('sort desc')->select()
            ]);
        }
    }

    public function product_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Product();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                case 'ishot':
                    $status = $cate['ishot'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function product_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Product();
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->update(['isdel' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function agentlog()
    {
        if ($this->request->isAjax()) {
            $model = new AgentLog();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['types'])) {
                $where[] = ['types', '=', $post['types']];
            }
            $where[] = ['user_id', '=', $this->request->agent['id']];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }


    public function quhuaall()
    {
        $model = new AgentArea();
        $agents = (new Agents())->where('top', $this->request->agent['id'])->column('id');
        $lists = $model->where('type', 5)->where(['agentid' => $agents])->field('substring(ploygongeo,10,length(ploygongeo)-11) as ploygongeo,id')->select();
        $arr = [];
        foreach ($lists as $list) {
            $list['ploygongeo'] = explode(',', $list['ploygongeo']) ?? [];
            $list['ploygongeo'] = array_slice($list['ploygongeo'], 0, -1);
            foreach ($list['ploygongeo'] as $key => $ploygongeo) {
                $ploygongeo = explode(' ', $ploygongeo) ?? [];
                $arr[$list['id']][] = $ploygongeo;
            }
        }
        array_multisort($arr);
        return view('', [
            'arr' => $arr
        ]);
    }

    public function agentarea_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new AgentArea();
            $agents = (new Agents())->where('top', $this->request->agent['id'])->column('id');
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $agents])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function agent_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Agents();
            $agents = (new Agents())->where('top', $this->request->agent['id'])->column('id');
            $agent = $model->where(['id' => $id, 'id' => $agents])->find();
            if (empty($agent)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'status':
                    if ($agent['status'] == 3) {
                        return json(['code' => 1, 'data' => [], 'msg' => '账号已被删除']);
                    }
                    $status = $agent['status'] == 1 ? 2 : 1;
                    break;
                case 'openid':
                    $status = null;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }
}
